package com.xiaoshuidi.cloud.module.contract.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaoshuidi.cloud.framework.tenant.core.job.TenantJob;
import com.xiaoshuidi.cloud.module.contract.controller.admin.contract.vo.ContractConfigReqVO;
import com.xiaoshuidi.cloud.module.contract.dal.dataobject.contract.ContractHouseOwnerDO;
import com.xiaoshuidi.cloud.module.contract.enums.contract.ContractOwnerStatusEnum;
import com.xiaoshuidi.cloud.module.contract.enums.contract.ContractSignStatusEnum;
import com.xiaoshuidi.cloud.module.contract.enums.contract.ContractTypeEnum;
import com.xiaoshuidi.cloud.module.contract.service.contract.ContractConfigService;
import com.xiaoshuidi.cloud.framework.tenant.core.util.TenantUtils;
import com.xiaoshuidi.cloud.module.contract.dal.dataobject.contract.ContractHouseOwnerDO;
import com.xiaoshuidi.cloud.module.contract.dal.mysql.contract.ContractHouseOwnerMapper;
import com.xiaoshuidi.cloud.module.contract.service.contract.ContractHouseOwnerService;
import com.xiaoshuidi.cloud.module.contract.service.contract.dto.ContractHouseOwnerQueryDTO;
import com.xiaoshuidi.cloud.module.contract.service.contract.dto.RentFreePeriodDTO;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

import static com.xiaoshuidi.cloud.module.contract.enums.ApiConstants.ZERO;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
@Component
@TenantJob
public class OwnerContractJob {
    @Resource
    private ContractHouseOwnerService contractHouseOwnerService;
    @Resource
    private ContractConfigService contractConfigService;
    @Resource
    private ContractHouseOwnerMapper contractHouseOwnerMapper;

    @XxlJob("renewal-owner-contract-change")
    @Transactional
    public void changeRenewalContractStatus() {
        log.info("业主续租合同状态变更 - 执行开始");
        String param = XxlJobHelper.getJobParam();
        LocalDate date = LocalDate.now();
        if (StringUtils.isNotBlank(param)){
            try {
                LocalDate paramDate = LocalDate.parse(param);
                if (paramDate.isBefore(date)){
                    date = paramDate;
                }
            } catch (Exception e) {
                log.error("业主续租合同状态变更,参数转换异常", e);
            }
        }
        LocalDate finalDate = date;
        contractHouseOwnerService.changeRenewalContractStatus(finalDate);
        log.info("业主续租合同状态变更 - 执行结束");
    }

    /**
     * 业主合同发起签约后自动失效
     * 发起签约后配置时间内业主未签约合同失效
     */
    @XxlJob("owner-initiate-sign-auto-expire")
    public void ownerInitiateSignAutoExpire() {
        log.info("业主合同发起签约后自动失效 - 执行开始");
        LocalDateTime now = LocalDateTime.now();
        ContractConfigReqVO contractConfigDO = contractConfigService.getContractConfig();
        if (Objects.isNull(contractConfigDO)){
            return;
        }
        Integer contractSignedAging = contractConfigDO.getOwnerContractSignedAging();
        if (!contractConfigDO.getOwnerContractSignedAgingStatus() || ZERO.intValue() >= contractSignedAging){
            return;
        }
        LocalDateTime dateTime = now.plusHours(-1 * contractSignedAging);
        // 查询合同 1租户 2平台签约时间小于等于限制时间 3在线签约状态-待乙方签约 4合同状态-待签约 5电子合同
        ContractHouseOwnerQueryDTO param = new ContractHouseOwnerQueryDTO();
        param.setLeLessorSignTime(dateTime);
        param.setSignStatus(ContractSignStatusEnum.SIGNED_PARTY_B.getCode());
        param.setContractStatus(ContractOwnerStatusEnum.NO_SIGNED.getCode());
        param.setContractType(ContractTypeEnum.ELECTRONIC.getCode());
        List<ContractHouseOwnerDO> contractHouseOwnerList = contractHouseOwnerService.getByParam(param);
        if (CollectionUtils.isNotEmpty(contractHouseOwnerList)){
            // 修改合同状态为已取消
            for (ContractHouseOwnerDO contractHouseOwnerDO : contractHouseOwnerList) {
                contractHouseOwnerService.cancelContract(contractHouseOwnerDO.getId());
            }
        }
        log.info("业主合同发起签约后自动失效 - 执行结束");
    }





    @XxlJob("owner-data-migration-free-period")
    @Transactional
    public void dataMigrationFreePeriod () {
        log.info("业主合同数据迁移免租期处理 - 执行开始");
        // 查询建行一期数据
        LambdaQueryWrapper<ContractHouseOwnerDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.isNotNull(ContractHouseOwnerDO::getOldId);
        List<ContractHouseOwnerDO> list = contractHouseOwnerMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(list)){
            for (ContractHouseOwnerDO contractHouseOwnerDO : list) {
                if (Objects.nonNull(contractHouseOwnerDO.getFirstPeriodMonth()) && Objects.nonNull(contractHouseOwnerDO.getSecondPeriodMonth())
                        && Objects.nonNull(contractHouseOwnerDO.getEntrustDate()) && Objects.nonNull(contractHouseOwnerDO.getEachCycleMonth())){
                    // 免租期处理
                    int years = contractHouseOwnerDO.getEntrustDate() / 12 + (contractHouseOwnerDO.getEntrustDate() % 12 != 0 ? 1 : 0);
                    List<RentFreePeriodDTO> freePeriodDTOS = new ArrayList<>();
                    int cycle = contractHouseOwnerDO.getEachCycleMonth() / 12;
                    for (int i = 1; i < years; i++) {
                        if (i == 1){
                            // 首期
                            RentFreePeriodDTO periodDTO = new RentFreePeriodDTO();
                            periodDTO.setYearNo(i);
                            periodDTO.setFreePeriodMonthNum(contractHouseOwnerDO.getFirstPeriodMonth());
                            freePeriodDTOS.add(periodDTO);
                            continue;
                        }
                        if (cycle == 1 || i % cycle == 1){
                            RentFreePeriodDTO periodDTO = new RentFreePeriodDTO();
                            periodDTO.setYearNo(i);
                            periodDTO.setFreePeriodMonthNum(contractHouseOwnerDO.getSecondPeriodMonth() < 0?0:contractHouseOwnerDO.getSecondPeriodMonth());
                            freePeriodDTOS.add(periodDTO);
                        }else {
                            RentFreePeriodDTO periodDTO = new RentFreePeriodDTO();
                            periodDTO.setYearNo(i);
                            periodDTO.setFreePeriodMonthNum(0);
                            freePeriodDTOS.add(periodDTO);
                        }
                    }
                    contractHouseOwnerDO.setRentFreePeriod(freePeriodDTOS);
                }
            }
            contractHouseOwnerMapper.updateBatch(list, list.size());
        }
        log.info("业主合同数据迁移免租期处理 - 执行结束");
    }


}
